libMob
	parent_type = /libBase
	name = "libMob"
	numVerP = 0
	numVerM = 0
	numVerR = 0

	Shutdown()		//called on shutdown or crash
		CleanseMobs()

	var
		tblMob = "core_CurrentMobs"

	proc

		CleanseMobs()
			Core.DB.runQuery("delete from `[tblMob]`")	//purge the current mob table of anything left in it: world is closing there are no current mobs

		createMobTable()

			if(existsMobTable()) return FALSE

			var/sql = {"
			CREATE TABLE `[Core.DB.getDB()]`.`[getMobTable()]` (
				mobID		varchar(50) NOT NULL,
				name		VARCHAR(255),
				location	VARCHAR(255),
				client		VARCHAR(2000),
				notes		VARCHAR(2000),
				added		DATETIME,
				updated		DATETIME,
				PRIMARY KEY	(`mobID`)
				) ENGINE=InnoDB;
			"}

			Core.DB.runQuery(sql)

			return existsMobTable()

		existsMobTable()
			var/DBQuery/q = Core.DB.Query("Describe [getMobTable()]")
			return q.Execute()

		setMobTable(tbl as text)
			tblMob = tbl

		getMobTable()
			return tblMob

		remMob(refstring)
			world.log<<"remMob([refstring])"
			Core.DB.establishConnection()
			var/DBQuery/q = Core.DB.Query("delete from `[tblMob]` where mobid = \"[refstring]\"")
			if(!q.Execute()) Core.Error.catchError("type=BD;source=libMob:libMob.remMob();error=Failed Query ([q.ErrorMsg()]);debug='Args=[refstring], SQL=delete from `[tblMob]` where mobid = \"[refstring]\"")
			return TRUE

		addMob(mob/m)
			world<<"ADDING MOB ..."
			Core.DB.establishConnection()
			var/DBQuery/q = Core.DB.Query("select * from `[tblMob]` where mobID = \"\ref[m]\"")
			if(!q.Execute()) Core.Error.catchError("type=DB;source=libMob:libMob.addMob();error=Failed Query ([q.ErrorMsg()]);debug='Args=[m], SQL='select * from `[tblMob]` where mobID = \ref[m]'")
			if(length(q.item))
				world<<"FOUND SOMETHING!"
				return FALSE
			else
				world<<"INSERTING DATA ..."
				createMobTable()
				Core.DB.insertData("tbl=[tblMob];mobID=\"\ref[m]\";name=\"[m.name]\";location=\"[m.loc]\";client=\"[m.client]\"")
				world<<"Done?"

		updateMob(mob/m)
			world.log<<"Update [m]!"
			var/sql = {"
			update `[getMobTable()]`
			set name = \"[m.name]\", location = \"[m.x],[m.y],[m.z]\", client=\"[m.client]\", updated=\"[Core.TimeStamp()]\"
			where mobID = \"\ref[m]\"
			"}
			Core.DB.runQuery(sql)

mob
	New()
		. = ..()
		Core.Mob.addMob(src)
		spawn(50) UpdateCurrent()
		return .

	Del()
		world.log<<"Deleting [src]"
		Core.Mob.remMob("\ref[src]")
		..()

	Login()
		..()
		Core.Mob.updateMob(src)

	proc
		UpdateCurrent()
			Core.Mob.updateMob(src)
			spawn(6000) UpdateCurrent()